package com.sky.utils;


import com.aliyun.oss.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;

@Slf4j
@Data
@AllArgsConstructor
public class AliOssUtil {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /*文件上传*/
    public String upload(byte[] bytes,String objectName){
        OSS  ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        try{
            ossClient.putObject(bucketName,objectName,new ByteArrayInputStream(bytes));
        }catch (OSSException oe){
            System.out.println("Caught an OssException");
        }
        catch (ClientException ce){
            System.out.println("Caught an ClientException");
        }
        finally {
            if(ossClient!=null){
                ossClient.shutdown();
            }
        }
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder.append(bucketName).append(".").append(endpoint).append("/").append(objectName);
        log.info("文件上传到:{}",stringBuilder.toString());
        return stringBuilder.toString();
    }


}
